/**
*@author zhongrd
*@file 第三方平台配置新增或编辑
*@date 2019/5/20 16:42
*/
<script>
  import { Form } from 'ant-design-vue'

  let uuid = 1;
  let keysMap=[];


  const DynamicFieldSet = {
    props:['cardData'],
    data(){
      return{
        name:'平台名称',
      }
    },
    mounted(){
      this.init()
    },
    methods: {
      //初始时显示一条属性
      init(){
        console.log(this.CollectionData( 'IDCARDTYPE'))
        const { form } = this

        let item = this.cardData.list;
        //判断是新增还是修改,若item长度大于0则为修改,初始化表单
        if(this.cardData.list){
          uuid=item.length;

          item.forEach((itemdata,index)=>{
              keysMap.push(index);

          })
          form.setFieldsValue({
            keys: keysMap
          })
        }else{
          form.setFieldsValue({
            keys: [0]
          })
        }
      },
      //删除属性
      remove  (k) {
        const { form } = this
        // can use datta-binding to get
        const keys = form.getFieldValue('keys')

        // We need at least one passenger
        if (keys.length === 1) {
          return
        }

        // can use datta-binding to set
        form.setFieldsValue({
          keys: keys.filter(key => key !== k)
        })
      },
      //添加属性
      add  () {
        const { form } = this
        // can use datta-binding to get
        const keys = form.getFieldValue('keys')
        const nextKeys = keys.concat(uuid)
        uuid++
        // can use datta-binding to set
        // important! notify form to detect changes
        form.setFieldsValue({
          keys: nextKeys,

        })
      },
      //提交表单
      handleSubmit  (e) {
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            let submitdata=[];
            let map ={};
            values.keys.forEach(item=>{
              map = {};
              map = {"name":values.name[item],"value":values.value[item],"key":values.key[item],"desc":values.desc[item]};
              submitdata.push(map);
            })
            let submitParameter={
              url:'msg/thirdPlatform/thirdPlatformController/add.do',
              data:{"msgThirdPlatformVoList":JSON.stringify(submitdata),"platformtype":values.select,"platformname":values.platformname}
            };
            let _this= this;
            Base.submit(_this,submitParameter,{
              successCallback:(data) => {
              if (data.errors === null) {

                const { form } = this
                form.setFieldsValue({
                  keys: [0],
                  name:[''],
                  key:[''],
                  value:[''],
                  desc:['']
                })
                _this.$message.success("新增成功!")
              } else {
                for (let i = 0; i < data.errors.length; i++) {
                  _this.$message.error(data.errors[i].msg)
                }
              }
            }
            })
          }
        })
      }
    },

    render () {
      const { getFieldDecorator, getFieldValue } = this.form
      const formItemLayout = {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      }
      const formItemLayoutWithOutLabel = {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 }
        }
      }
      getFieldDecorator('keys', { initialValue: [] })
      const keys = getFieldValue('keys')
      const formItems = keys.map((k, index) => {
        return (
          <ta-row gutter={24}>
          <ta-col span={6}>
          <ta-form-item
        {...{ props: formItemLayout  }}
        label='name'
        required={false}
        key={k}
          >
          {getFieldDecorator(`name[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            required: true,
            whitespace: true,
            message: "请填写属性名称"
          }]
        })(
        <ta-input placeholder='请输入属性名称' style={{ width: '60%', marginRight: '8px' }} />
      )}
      </ta-form-item>
          </ta-col>
        <ta-col span={6}>
          <ta-form-item
        {...{ props: formItemLayout  }}
        label='key'
        required={false}
        key={k}
          >
          {getFieldDecorator(`key[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            required: true,
            whitespace: true,
            message: "请填写属性key"
          }]
        })(
        <ta-input placeholder='请输入key' style={{ width: '60%', marginRight: '8px' }} />
      )}
      </ta-form-item>
        </ta-col>
        <ta-col span={6}>
          <ta-form-item
        {...{ props: formItemLayout  }}
        label='value'
        required={false}
        key={k}
          >
          {getFieldDecorator(`value[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            required: true,
            whitespace: true,
            message: "请填写属性值"
          }]
        })(
        <ta-input placeholder='请输入值' style={{ width: '60%', marginRight: '8px' }} />
      )}
      </ta-form-item>
        </ta-col>
        <ta-col span={6}>
          <ta-form-item
        {...{ props: formItemLayout  }}
        label='描述'
        required={false}
        key={k}
          >
          {getFieldDecorator(`desc[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          rules: [{
            required: false,
            whitespace: true,
            message: "Please input passenger's name or delete this field."
          }]
        })(
        <ta-input placeholder='请输入描述' style={{ width: '60%', marginRight: '8px' }} />
      )}
        {keys.length > 1 ? (
          <ta-icon
          class='dynamic-delete-button'
          type='minus-circle-o'
          disabled={keys.length === 1}
          onClick={() => this.remove(k)}
          />
        ) : null}
      </ta-form-item>
        </ta-col>
        </ta-row>
      )
      })
      return (
        <ta-form onSubmit={this.handleSubmit}>
        <ta-form-item label="所属平台:">
        {getFieldDecorator('select', {
        rules: [
          { required: true, message: 'Please select your country!' }
        ]
      })(
        <ta-select>
          <ta-select-option value='1'>短信平台</ta-select-option>
          <ta-select-option value='2'>推送平台</ta-select-option>
        </ta-select>
      )}
        </ta-form-item>
      <ta-form-item label="平台名称:">
        {getFieldDecorator('platformname', {
        rules: [
          { required: true, message: '请输入平台名称' }
        ]
      })(
      <ta-input placeholder='请输入描述' style={{ width: '60%', marginRight: '8px' }} />
    )}
    </ta-form-item>
        {formItems}
        <ta-form-item {...{ props: formItemLayoutWithOutLabel }}>
    <ta-button type='dashed' onClick={this.add} style={{ width: '60%' }}>
    <ta-icon type='plus' /> Add field
      </ta-button>
      </ta-form-item>
      <ta-form-item {...{ props: formItemLayoutWithOutLabel }}>
    <ta-button type='primary' htmlType='submit'>Submit</ta-button>
        </ta-form-item>
        </ta-form>
    )
    }
  }
  //编辑时页面赋值
  function mapStateToProps(props){
    let data={};
    let item = props.cardData.list
    if(props.cardData.list){
      uuid=item.length;

      item.forEach((itemdata,index)=>{
        data['name['+index+']']=Form.createFormField({
          value:itemdata.name
        })
        data['key['+index+']']=Form.createFormField({
          value:itemdata.key
        })
        data['value['+index+']']=Form.createFormField({
          value:itemdata.value
        })
        data['desc['+index+']']=Form.createFormField({
          value:itemdata.desc
        })
      })
    }
    data['select']=Form.createFormField({
      value:item[0].platformtype
    })
    data['platformname'] = Form.createFormField({
      value:item[0].platformname
    })
    console.log(data)
    return data
  }
  export default Form.create({mapPropsToFields:mapStateToProps})(DynamicFieldSet)

</script>
<style>
  .dynamic-delete-button {
    cursor: pointer;
    position: relative;
    top: 4px;
    font-size: 24px;
    color: #999;
    transition: all .3s;
  }
  .dynamic-delete-button:hover {
    color: #777;
  }
  .dynamic-delete-button[disabled] {
    cursor: not-allowed;
    opacity: 0.5;
  }
</style>
